package com.wanmait.wisdom.web.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wanmait.wisdom.entity.Rapair;
import com.wanmait.wisdom.util.AjaxResult;
import com.wanmait.wisdom.web.service.WebRapairService;
import org.apache.commons.io.FilenameUtils;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;


@RestController
@RequestMapping("web")
public class WebRapairController {

    @Resource
    private WebRapairService webRapairService;

    @PostMapping("insert")
    public AjaxResult insert(@RequestBody Rapair repair){
        webRapairService.insertRapair(repair);
        return  AjaxResult.success();
    }
    @PostMapping("selectAllByResidentId")
    public AjaxResult selectAllByResidentId(@RequestBody Rapair rapair, Date startTime,Date endTime, Integer pageNum){
        if (pageNum==null){
            pageNum=1;
        }
        int pageSize=10;
        PageInfo<Rapair> pageInfo=webRapairService.selectAllRapair(rapair,startTime,endTime,pageNum,pageSize);
        return AjaxResult.success().put("pageInfo",pageInfo);
    }
    //图片保存
    @PostMapping("uploadWangEditorPic")
    public AjaxResult uploadWangEditorPic(MultipartFile file){
        try {
            String path= ResourceUtils.getURL("classpath:").getPath()+"/static/picture";
            String fileName = UUID.randomUUID().toString() .replaceAll("-","")+"."+ FilenameUtils.getExtension(file.getOriginalFilename());
            file.transferTo(new File(path,fileName));
            return AjaxResult.success("上传成功").put("fileName",fileName);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return AjaxResult.error("上传失败");
    }
    //添加报修信息
    @PostMapping("add")
    public AjaxResult addRapair(@RequestBody Rapair repair){
        webRapairService.insertRapair(repair);
        return AjaxResult.success("添加成功");
    }
    //根据id获取报修信息
    @GetMapping("{id:\\d+}")
    public AjaxResult selectById(@PathVariable Integer id){
        Rapair rapair = webRapairService.selectById(id);
        return AjaxResult.success().put("rapair",rapair);
    }
    //根据ID删除报修
    @PostMapping("{id:\\d+}")
    public AjaxResult deleteById(@PathVariable Integer id){
        webRapairService.deleteById(id);
        return AjaxResult.success("撤销成功");
    }


}
